from django.shortcuts import render
from django.views import View
from areas.models import Area
from django.http import JsonResponse
from django.core.cache import cache


# # 省级数据
# class ProvinceAreasView(View):
#     def get(self, request):
#
#         # 读取缓存
#         if not cache.get('province_list'):
#
#             try:
#                 # 1.查询省级数据
#                 province_model_list = Area.objects.filter(parent__isnull=True)
#
#                 # 2.整理省级数据
#                 province_list = []
#                 for province in province_model_list:
#                     province_list.append({
#                         "id": province.id,
#                         "name": province.name
#                     })
#
#                 # 设置缓存
#                 cache.set('province_list', province_list, 3600)
#
#             except Exception as e:
#                 # 3.数据出错
#                 return JsonResponse({'code': 400, 'errmsg': '省份数据错误'})
#
#         # 4.数据正常
#         return JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': cache.get('province_list')})
#
#
# # 市级数据
# class SubAreasView(View):
#     def get(self, request, pk):
#         # 1.读取缓存
#         if not cache.get(f'sub_data_{pk}'):
#             try:
#                 # 2.没有缓存
#                 # 查询市\区数据
#                 sub_model_list = Area.objects.filter(parent=pk)
#
#                 # 查询省级数据
#                 parent = Area.objects.get(id=pk)
#
#                 # 市\区级数据
#                 subs = []
#
#                 for sub_model in sub_model_list:
#                     subs.append({'id': sub_model.id,
#                                  'name': sub_model.name})
#
#                 # 返回数据格式
#                 sub_data = {
#                     "id": parent.id,
#                     "name": parent.name,
#                     "subs": subs,
#                 }
#
#                 # 添加缓存
#                 cache.set(f'sub_data_{pk}', sub_data, 3600)
#
#             except Exception as e:
#                 return JsonResponse({'code': 400, 'errmsg': '城市或区县数据错误'})
#
#         # 3.有缓存
#         return JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': cache.get(f'sub_data_{pk}')})


from rest_framework.generics import ListAPIView, RetrieveAPIView, GenericAPIView
from areas.serializers import AreaModelSerializer
from rest_framework.response import Response


class ProvinceAreasSerializer(ListAPIView):
    queryset = Area.objects.all()
    serializer_class = AreaModelSerializer


class SubAreasSerializer(RetrieveAPIView):
    queryset = Area.objects.all()
    serializer_class = AreaModelSerializer
